< previous page page_315 next page >

Page 315
Packing Integers into Long Variables
There is one special case, very similar to bitfields, that is seen frequently when using the Win32 API. You've seen that bitfields allow you to pack groups of one or more bits into a single 32-bit Long variable. You know that a VB integer variable is 16 bits. Clearly, it is possible to pack two 16-bit integers into a 32-bit long variable. A classic example of this is when two 16-bit mouse coordinates are packed into a long value for the internal Windows mouse messages. The X mouse coordinate is kept in the lower 16-bit integer, the Y coordinate in the upper integer.
To combine integers X and Y into long variable L, do the following:
Dim XL As Long, YL As Long
' Both values are converted into Longs in order to prevent overflows.
' They are masked with &H7FFF to eliminate errors due to sign extension
XL = X And &H07FFF&
YL = Y And &H07FFF&
YL = YL * &H10000&
To divide long variable L into integers X and Y, do the following:
Dim XL As Long, YL As Long
XL = L And &H07FFF&                ' Extract the X value
X = XL                             ' Because of the mask we chose,
                                     there can be no overflow
YL = L And &H7FFFOOOO&
YL = YL / &H10000&
Y = YL
This example will only work with positive integer variables. With negative values, you have to take additional steps to prevent possible overflow errors. That's why this kind of packing and unpacking is often best done in a DLL support library written in C++, such as the apigid32.dll DLL included with this book. Refer to Appendix C, which describes the agDWORDto2Integers and agPOINTStoLong functions that can be used to perform these operations.

 
< previous page page_315 next page >